package com.lxm.sevice.wx;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lxm.dao.WxMapperDao;
import com.lxm.entity.UserEntity;
import com.lxm.entity.wx.WxAcceptEntity;
import com.lxm.util.HttpUtils;
import com.lxm.util.Utils;
import com.lxm.util.XmlUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/24 16:04
 */
@Service
public class WxServiceImpl implements WxService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    static String defaultName = "初始化昵称";
    static String defaultHeadUrl = "http://thirdwx.qlogo.cn/mmopen/ajNVdqHZLLBJo7m2c9MsnsK0VOcqtUMfcNxfe3EnbH3sPfoJGnKWgWxgeBl0BkibcfnibmwGAAWHh4LSwWE4jXDw/132";

    static String getUserUrl = "https://api.weixin.qq.com/cgi-bin/user/info";

    @Resource
    private RedisTemplate<String, String> auctionRedisTemplate;
    @Autowired
    private WxMapperDao wxMapperDao;

    public void wxLogin(WxAcceptEntity wxAcceptEntity) {
        UserEntity userEntity = new UserEntity();
        String fromUserName = wxAcceptEntity.getFromUserName();
        userEntity.setWxOperId(fromUserName);
        UserEntity userEntity1 = wxMapperDao.queryUserData(userEntity);
        if (!Objects.nonNull(userEntity1)) {
            userEntity1 = saveUser(wxAcceptEntity);
        }
        String eventKey = wxAcceptEntity.getEventKey();
        if (eventKey.isEmpty()) {
            return;
        }
        String[] split = eventKey.split("#");
        String token = split[1];
        ValueOperations<String, String> stringStringValueOperations = auctionRedisTemplate.opsForValue();
        JSONObject data = new JSONObject();
        data.put("code", 1);
        data.put("info", userEntity1);
        stringStringValueOperations.set(token, data.toJSONString(),1,TimeUnit.HOURS);
    }


    public void updateUser(WxAcceptEntity wxAcceptEntity) {
        String fromUserName = wxAcceptEntity.getFromUserName();
        JSONObject user = getUserInfoByOpenId(fromUserName);
        if ("0".equals(user.getString("subscribe"))) {
            return;
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(user.getString("nickname"));
        userEntity.setWxOperId(fromUserName);
        userEntity.setHeadUrl(user.getString("headimgurl"));
        wxMapperDao.update(userEntity);
    }

    public UserEntity saveUser(WxAcceptEntity wxAcceptEntity) {
        String fromUserName = wxAcceptEntity.getFromUserName();
        JSONObject user = getUserInfoByOpenId(fromUserName);
        if ("0".equals(user.getString("subscribe"))) {
            return null;
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(Objects.requireNonNullElse(user.getString("nickname"), defaultName));
        userEntity.setWxOperId(fromUserName);
        userEntity.setHeadUrl(Objects.requireNonNullElse(user.getString("headimgurl"), defaultHeadUrl));
        userEntity.setPassWord("12345678");
        userEntity.setCreateTime(new Date());
        userEntity.setAuthCode(Utils.getAuthCode());
        userEntity.setUserType("1");
        userEntity.setMaxSenNum(1000);
        userEntity.setCurrentSenNum(0);
        userEntity.setOneDayNum(0);
        userEntity.setTodayMaxNum(20);
        userEntity.setUserState("0");
        wxMapperDao.insert(userEntity);
        return userEntity;
    }

    /**
     * @param openId 用户的openId
     * @return 用户的信息
     */
    public JSONObject getUserInfoByOpenId(String openId) {
        ValueOperations<String, String> stringStringValueOperations = auctionRedisTemplate.opsForValue();
        String token = stringStringValueOperations.get("token");
        JSONObject reuslt = new JSONObject();
        reuslt.put("access_token", token);
        reuslt.put("openid", openId);
        reuslt.put("lang", "zh_CN");
        return HttpUtils.post(getUserUrl, reuslt.toJSONString());
    }


    public String senWxText(WxAcceptEntity wxAcceptEntity) throws JsonProcessingException {
        String fromUserName = wxAcceptEntity.getFromUserName();
        String toUserName = wxAcceptEntity.getToUserName();
        wxAcceptEntity.setFromUserName(toUserName);
        wxAcceptEntity.setToUserName(fromUserName);
        wxAcceptEntity.setMsgType("text");
        wxAcceptEntity.setEvent(null);
        wxAcceptEntity.setCreateTime(String.valueOf(new Date().getTime()));
        return XmlUtils.beanToXml(wxAcceptEntity);
    }


    public String getQrcode() {
        ValueOperations<String, String> stringStringValueOperations = auctionRedisTemplate.opsForValue();
        String token = stringStringValueOperations.get("token");
        String getQrcodeUrl="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";
        getQrcodeUrl =String.format(getQrcodeUrl,token);
        String userToken = Utils.getUserToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expire_seconds",30);
        jsonObject.put("action_name","QR_STR_SCENE");
        jsonObject.put("action_info",new JSONObject().fluentPut("scene",new JSONObject().fluentPut("scene_str","login#"+userToken)));
        JSONObject post = HttpUtils.post(getQrcodeUrl, jsonObject.toJSONString());
        JSONObject relust =new JSONObject();
        relust.put("userToken",userToken);
        relust.put("img","https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+post.getString("ticket"));
        JSONObject user = new JSONObject();
        user.put("code",0);
        stringStringValueOperations.set(userToken,user.toJSONString(),30, TimeUnit.SECONDS);
        return relust.toJSONString();

    }

    public Map<String,String> queryMdDataById(String id){
        return wxMapperDao.queryMdDataById(id);
    }
    public List<Map<String,String>> queryAllQQInfo(){
        return wxMapperDao.queryAllQQInfo();
    }
    public void upDateMdDataById(String id,  String content){
        wxMapperDao.upDateMdDataById(id, content);
    }
}
